<?php
/**
 * Created by PhpStorm.
 * User: yuqing
 * Date: 15-10-10
 * Time: 下午12:14
 */
class Controller_supactsync extends Controller_Admin
{
    public function before()
    {
        try {
            ACL::Required('supplier bankinfo check edit');
        } catch (HTTP_Exception_403 $e) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        parent::before();
    }

    public function Action_index()
    {
        $this->title = __('帐号同步');

        $view = View::factory('supactsync/index');
        $this->response->body($view);
    }

    //账号同步方法
    public function Action_sync()
    {
        $result = array(
            'code' => '',
            'errormsg' => '',
            'success' => array()
        );
        $getpostr = $_POST['puids'];
        //替换字符串
        $postr = preg_replace("/(\n)|(\s)|(\t)|(，)/", ',', $getpostr);
        $arr = explode(',', $postr);

        foreach ($arr as $v) {
            if (!is_numeric($v)) {
                $result['code'] = 'n';
                $result['errormsg'] = $v . '中存在非法字符';
                exit(json_encode($result));
            }
            //需要判断采购单是否是可以修改的。
            $sql = "SELECT `status` FROM `purchaseorders` WHERE `id`= $v";
            $res = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
            if ($res[0]['status'] > 70) {
                $result['code'] = 'n';
                $result['errormsg'] = $v . '  已经完结不能修改';
                exit(json_encode($result));
            }
        }
//1根据采购单找到供应商ID
        $supplierId = $this->getsuid($postr);

        if (!$supplierId) {
            $result['code'] = 'n';
            $result['errormsg'] = '不存在该供应商';
            exit(json_encode($result));
        }
//2根据供应商ID找到可用的付款帐号ID及付款方式 （存在多个可用的ID时取最新的）
//3根据付款帐号ID找到付款币种
        $accArr = $this->getaccountmsg($supplierId);

//4更新采购单 币种 汇率类型
        $sql = "UPDATE `newerp`.`purchaseorders` SET `coin` = ".$accArr['coin']." , `pay_way` = ".$accArr['payway'] ;

        !empty($_POST['ratetype']) && ($_POST['ratetype'] != '') && $sql .= " ,`ratetype` = " . $_POST['ratetype'];

        $sql .= " WHERE `id` IN ($postr);";

        $ponum = DB::query(Database::UPDATE, $sql)->execute('newerp');

//5更新供应商付款表
        $sql = "UPDATE `purchasesupplier` SET `pay_way_id` = ".$accArr['payway'].",
                `payaccountinfo_id` = ".$accArr['account_id']." WHERE `poid` IN ($postr)";
        $pusunum = DB::query(Database::UPDATE, $sql)->execute('newerp');

//6在供应商应付帐款修改ord_plan  ord——change

        $sql = "UPDATE `ord_plan` SET `ac_id` = ".$accArr['account_id'].",
                `pay_way` = ".$accArr['payway'].",
                `coin` = ".$accArr['coin']."
                WHERE `pu_id` IN ($postr)";
        DB::query(Database::UPDATE,$sql)->execute('accoubtsystem');

        $sql = "UPDATE `ord_change` SET `ac_id` = ".$accArr['account_id'].",
                `pay_way` = ".$accArr['payway'].",
                `coin` = ".$accArr['coin']."
                WHERE `pu_id` IN ($postr)";

        DB::query(Database::UPDATE,$sql)->execute('accoubtsystem');
//7输出成功信息
        $result['code'] = 200;
        $result['success'] = array('ponum' => $ponum, 'pusunum' => $pusunum);
        exit(json_encode($result));

//        $coin = '';
//        empty($coin)&&empty($sql)?$sql.="set `coin` = $coin":",set `coin` = $coin";
    }

    public function Action_getPurchaseMsg()
    {
        $getpostr = $_GET['puids'];
        //替换字符串
        $postr = preg_replace("/(，)|(\s)/", ',', $getpostr);
        $arr = explode(',', $postr);
        $result = array(
            'code' => '',
            'errormsg' => '',
            'msg' => array()
        );
        foreach ($arr as $v) {
            if (!is_numeric($v)) {
                $result['code'] = 465;
                $result['errormsg'] = $v . ' 中存在非法字符';
                exit(json_encode($result));
            }
//需要判断采购单是否是可以修改的。
            $sql = "SELECT `status` FROM `purchaseorders` WHERE `id`= $v";
            $res = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
            if ($res[0]['status'] > 70) {
                $result['code'] = 465;
                $result['errormsg'] = $v . '  订单已经完结不能修改';
                exit(json_encode($result));
            }
            $this->getsuid($postr);

//获取采购单信息
            $sql = "SELECT po.`id` AS id,`supplier_id`, `purchaseorder_date` AS p_date, po.`coin` AS coin, `ratetype` , s.`value` AS status,`pay_way` , `transportation_expense` , TRUNCATE(`money`,2) as money,`remark`
                    FROM `purchaseorders` po LEFT JOIN `statusdics` s
                    ON ( po.`status` = s.`number`
                    AND s.`table` = 'purchaseorders'
                    AND s.`colum_name` = 'status' )
                    WHERE po.`id`
                    IN ($postr)";
            $pos = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array('id');

            $sql = "SELECT `id` , `paywayname`
                    FROM `payways`
                    WHERE `status` =0";
            $payways = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array('id','paywayname');

            $coins = array(1=>'人民币',2=>'美金',3=>'港币');
            $ratetypes = array(0=>'无',10=>'卖出价',20=>'中间价',30=>'自定义');
            $showMsg = array();
            foreach($pos as $poid=>$po){
                $showMsg['purchaseorder'][$poid]['date']            = $po['p_date'];
                $showMsg['purchaseorder'][$poid]['suid']            = $po['supplier_id'];
                $showMsg['purchaseorder'][$poid]['coin']            = $coins[$po['coin']];
                $showMsg['purchaseorder'][$poid]['ratetype']        = $ratetypes[$po['ratetype']];
                $showMsg['purchaseorder'][$poid]['status']          = $po['status'];
                $showMsg['purchaseorder'][$poid]['payway']          = $payways[$po['pay_way']];
                $showMsg['purchaseorder'][$poid]['trans_expense']   = $po['transportation_expense'];
                $showMsg['purchaseorder'][$poid]['money']           = $po['money'];
                $showMsg['purchaseorder'][$poid]['remark']          = $po['remark'];
            }
//获取供应商及帐号信息

            $supplierId     = $this->getsuid($postr);
            $supplier_name  = Newerpclientapi::getSuppliers(array('name'),array('id'=>"=".$supplierId));
            $accountmsg     = $this->getaccountmsg($supplierId);

            $showMsg['supplier']['su']['suid']                            = $supplierId;
            $showMsg['supplier']['su']['name']                            = $supplier_name[0]['name'];
            $showMsg['supplier']['su']['payway']                          = $payways[$accountmsg['payway']];
            $showMsg['supplier']['su']['account_id']                      = $accountmsg['account_id'];
            $showMsg['supplier']['su']['coin']                            = $coins[$accountmsg['coin']];
            $showMsg['supplier']['su']['bankname']                        = $accountmsg['bankname'];
            $showMsg['supplier']['su']['bankaccountname']                 = $accountmsg['bankaccountname'];
            $showMsg['supplier']['su']['bankaccount']                     = $accountmsg['bankaccount'];

            $result['code'] = 200;
            $result['errormsg'] = '';
            $result['view'] = View::factory('supactsync/pomsg')->set('showmsg',$showMsg)->render();

            exit(json_encode($result));
        }


    }
    private function getsuid($puid){
        $sql = "SELECT DISTINCT `supplier_id`
                FROM `purchaseorders`
                WHERE `id`
                IN ($puid)";
            $sup = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
        if(count($sup)>1){
            $result['code'] = 'n';
            $result['errormsg'] = '订单中存在多个供应商';
            exit(json_encode($result));
        }
        return $sup[0]['supplier_id'];

    }
    private function getaccountmsg($suid){
        //根据供应商ID找到可用的付款帐号ID及付款方式 （存在多个可用的ID时取最新的）

        $sql = "SELECT `payways_id` , `payaccountinfo_id`
                FROM `supplierpayaccount`
                WHERE `supplier_id` = $suid AND `active_status`= 1 AND `check_status` = 5
                ORDER BY `createtime` DESC";
        $supplierAccount = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
        if (count($supplierAccount) > 1) {
            $result['code'] = 'n';
            $result['errormsg'] = '请停用不使用的供应商帐号,勿删除!';
            exit(json_encode($result));
        }
        $payaccountinfo_id = $supplierAccount[0]['payaccountinfo_id'];
        if ($payaccountinfo_id) {

            $payways = $supplierAccount[0]['payways_id'];

        } else {
            $result['code'] = 'n';
            $result['errormsg'] = '没有最新的供应商帐号';
            exit(json_encode($result));
        }

        //根据付款帐号ID找到付款币种
        $sql = "SELECT `coinid`,`bankname`,`bankaccountname`,`bankaccount`  FROM `payaccountinfo` WHERE `id` = $payaccountinfo_id AND isuse = 1";
        $res = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();

        return array(
            'payway'=>$payways,
            'account_id'=>$payaccountinfo_id,
            'coin'=>$res[0]['coinid'],
            'bankname'=>$res[0]['bankname'],
            'bankaccountname'=>$res[0]['bankaccountname'],
            'bankaccount'=>$res[0]['bankaccount']
        );
    }

}

